const Seller = require('../model/Seller');
const Buller = require('../model/Buller');
const Good = require('../model/Good');
const Follow = require('../model/Follow');
const Like = require('../model/Likes');
const Ding = require('../model/Ding');

//验证模块
const validator = require('validator');
//db中有增加数据方法
const DbSet = require('../model/db');
const setting = require('../setting');
const auth = require('../common/auth');
const mail = require('../common/mail');
const multer = require('multer');

exports.regist = (req, res, next) => {
	console.log(req.body);
	var uname = req.body.uname;
	var pwd = req.body.pwd;
	var email = req.body.email;

	var error = ''
	if(!validator.matches(uname, /^[a-zA-Z0-9\-\.\+\*_ \u4e00-\u9fa5]{3,9}$/)) {
		error = '账号为3-11位'
	}
	if(!validator.matches(pwd, /^[a-zA-Z0-9\-\.\+\*_\@\#\!\?\$]{6,12}$/, 'g')) {
		error = '密码不合法，长度为5-11';
	}

	if(!validator.isEmail(email)) {

		error = '邮箱不合法'

	}
	if(error) {
		return res.end(error);
	}

	Buller.getBullerByName(uname, function(err, buller) {

		if(err) {
			return res.end(err);
		}
		if(buller) {
			return res.end('该用户名已注册');
		}
		Buller.getBullerByEmail(email, function(err, buller1) {
			if(err) {
				return res.end(err);
			}
			if(buller1) {
				return res.end('该邮箱已注册');
			}

			let newPwd = DbSet.encrypt(pwd, setting.PSDkey);
			req.body.pwd = newPwd;
			let reqMsg = {
				name: uname,
				email: email
			}
			console.log(req.body);
			mail.sendMails(reqMsg, function(err, info) {
				if(err) {
					console.log('邮件发送失败！');
				}
			})

			DbSet.addOne(req, res, Buller, req.body);

		})

	})

}
exports.login = (req, res, next) => {
	console.log(req.body);

	var uname = req.body.uname;
	var pwd = req.body.pwd;
	var isName = '';

	if(validator.matches(uname, /^[a-zA-Z0-9\-\.\+\*_ \u4e00-\u9fa5]{3,9}$/)) {
		isName = Buller.getBullerByName;
	}
	if(validator.isEmail(uname)) {
		isName = Buller.getBullerByEmail;
	}

	if(isName !== '') {

		isName(uname, function(err, buller) {

			if(err) {
				return res.end(err);
			}
			if(!buller) {
				return res.end('该用户不存在');
			}
			if(buller.isDis == true) {
				return res.end('该账号已被封禁');
			}

			var newPwd = DbSet.encrypt(pwd, setting.PSDkey);

			if(newPwd == buller.pwd) {

				auth.create_cookie_buller(buller, res);
				//购物车信息

				res.json({
					msg: 'success',
					buller
				});

			} else {
				res.end('密码错误！')
			}

		})

	} else {
		return res.end('格式错误');
	}

}
exports.checkLogin = (req, res, next) => {

	if(req.session.buller) {

		var id = req.session.buller._id;

		Buller.getBullerById(id, (err, buller) => {
			if(err) {
				return res.end(err);
			}

			req.session.buller = buller;
			res.json({
				data: buller
			});

		})

	} else {

		res.json({
			error: 1,
			data: null
		});

	}

}

exports.out = function(req, res, next) {
	req.session.buller = null;
	res.clearCookie(setting.user_cookie_name); // 清空cookie
	req.session.bullerLogin = false;
	res.json({
		err: 0,
		msg: 'success'
	});
}

exports.changeInfo = (req, res, next) => {
	var id = req.session.buller._id;
	for(key in req.body) {
		if(req.body[key] == '') {
			delete req.body[key];
		}
	}
	Buller.updateBuller(id, req.body, (err, buller) => {

		if(err) {
			return res.end(err);
		}

		Buller.getBullerById(id, (err, data) => {

			if(err) {
				return res.end(err);
			}

			res.json({
				msg: 'success',
				buller: data
			});
		})

	})

}

exports.goodsList = (req, res, next) => {

	var page = parseInt(req.query.page)

	if(!page) {
		page = 1;
	}

	Good.find({
		deleted: false
	}).populate('king_id').skip(8 * (page - 1)).limit(8).exec(function(err, data) {
		if(err) {
			return res.json({
				err: 1,
				mes: err.toString()
			});
		}

		if(req.session.buller) {
			return res.json({
				error: 0,
				msg: '收到了',
				data,
				user: req.session.buller
			})
		} else {
			return res.json({
				error: 0,
				msg: '收到了',
				data,
				user: null
			})
		}

	})

}
exports.search = (req, res, next) => {

	var query = req.body;

	var page = parseInt(query['page']);

	if(!page) {
		page = 1;
	}

	var name = query['name'];
	if(name) {

		if(req.session.buller) {

			Buller.getBullerById(req.session.buller._id, (err, buller) => {
				var cun = false;
				for(var i = 0; i < buller.hisSearch.length; i++) {

					if(buller.hisSearch[i] == name) {
						cun = true;
					}

				}
				if(!cun) {
					buller.hisSearch.unshift(name);
					buller.save();
				}

			})

		}

		var pattern = new RegExp("^.*" + query['name'] + ".*$");

		query.$or = [{
			'name': pattern
		}, {
			'describe': pattern
		}];
		delete query['name'];

	}

	delete query['page'];

	query.deleted = false;

	var start = parseInt(req.query.start);
	var end = parseInt(req.query.end);

	if(!start) {
		var start = 0;
		var end = 99999999999999999999999999;
	}

	var xu = req.query.xu;
	if(xu) {
		xu = parseInt(xu);
	} else {
		xu = 1;
	}

	console.log('das');
	Good.find({
		price: {
			$gte: start,
			$lte: end
		}
	}).find(query).populate('king_id').sort({
		'price': xu
	}).skip(8 * (page - 1)).limit(8).exec(function(err, data) {
		if(err) {
			return res.json({
				err: 1,
				mes: err.toString()
			});
		}

		if(data.length <= 0) {

			if(req.session.buller) {
				return res.json({
					error: 0,
					msg: '收到了',
					data,
					user: req.session.buller
				})
			} else {
				return res.json({
					error: 0,
					msg: '收到了',
					data,
					user: null
				})
			}

		}

		if(req.session.buller) {
			res.json({
				error: 0,
				msg: '收到了',
				data,
				user: req.session.buller
			})
		} else {
			res.json({
				error: 0,
				msg: '收到了',
				data,
				user: null
			})
		}

	})

}
exports.checkSearch = (req, res, next) => {

	if(req.session.buller) {
		Buller.getBullerById(req.session.buller._id, (err, buller) => {
			if(err) {
				return res.end(err);
			}
			buller.hisSearch = buller.hisSearch.slice(0, 10);
			buller.save();
			res.json({
				hisSearch: buller.hisSearch.slice(0, 10)
			});

		})
	} else {
		res.end(null);
	}

}

exports.addArea = (req, res, next) => {
	console.log(req.body);

	if(!req.session.buller) {
		return res.end('fail');
	}

	Buller.getBullerById(req.session.buller._id, (err, buller) => {
		if(err) {
			return res.end(err);
		}
		buller.area.push(req.body);

		if(buller.area.length == 1) {
			buller.area[0].index = true;
		}
		buller = new Buller(buller);
		req.session.buller = buller;
		buller.save();

		res.end('success');

	})

}
exports.removeArea = (req, res, next) => {
	if(!req.session.buller) {
		return res.end('fail');
	}
	var ins = req.query.ins;
	Buller.getBullerById(req.session.buller._id, (err, buller) => {
		if(err) {
			return res.end(err);
		}

		if(!req.query.edit) {
			buller.area.splice(ins, 1);
			buller = new Buller(buller);

		} else {
			for(var i = 0; i < buller.area.length; i++) {
				buller.area[i].index = false;
			}
			buller.area[ins].index = true;
			buller = new Buller(buller);
		}

		req.session.buller = buller;
		buller.save();
		res.json({
			msg: 'success',
			buller
		});

	})
}

exports.myFollow = (req, res, next) => {
	if(!req.session.buller) {
		return res.end('fail');
	}
	var king_id = req.session.buller._id;
	Follow.getFollowsByKing(king_id, (err, follows) => {
		if(err) {
			return res.end(err);
		}

		res.json({
			follows
		});

	})

}
exports.myLikes = (req, res, next) => {
	if(!req.session.buller) {
		return res.end('fail');
	}
	var king_id = req.session.buller._id;
	Like.getLikesByKing(king_id, (err, likes) => {
		if(err) {
			return res.end(err);
		}

		res.json({
			likes
		});

	})

}

exports.checkFollow = (req, res, next) => {

	if(!req.session.buller) {
		return res.end('fail');
	}

	var king_id = req.session.buller._id;
	var store_id = req.query.store_id;

	Follow.getFollowById(store_id, king_id, (err, follow) => {
		if(err) {
			return res.end(err);
		}

		if(!follow) {

			return res.json({
				follow: false
			});
		}
		res.json({
			follow: true
		});

	})

}

exports.dingArray = (req, res, next) => {
	if(!req.session.buller) {
		return res.end('fail');
	}
	var buller_id = req.session.buller._id;

	var dings = req.body.dings;
	var area = req.body.area;

	Ding.getDingsByBuller({
		'king_id': buller_id
	}, (err, dings) => {
		if(err) {
			return res.end(err);
		}
		dings.forEach(function(item) {
			item.newDing = false;
			item.save();
		})

	})

	for(var i = 0; i < dings.length; i++) {
		var ding = {};

		ding.seller_id = dings[i].king_id;
		ding.king_id = buller_id;
		ding.good_id = dings[i]._id;
		ding.color = dings[i].color[0];
		ding.model = dings[i].model[0];
		ding.num = dings[i].num;
		ding.area = req.body.area;
		var newDing = new Ding(ding);
		newDing.save();

	}

	res.end('success');

}

exports.dingOne = (req, res, next) => {

	if(!req.session.buller) {
		return res.end('fail');
	}
	var good_id = req.body.good._id;
	var seller_id = req.body.good.king_id._id;
	var buller_id = req.session.buller._id;
	var area = req.body.area;

	Ding.getDingsByBuller({
		'king_id': buller_id
	}, (err, dings) => {
		if(err) {
			return res.end(err);
		}
		dings.forEach(function(item) {
			item.newDing = false;
			item.save();
		})

	})

	var ding = new Ding({

		num: req.body.num,
		color: req.body.color,
		model: req.body.model,
		king_id: buller_id,
		seller_id,
		good_id,
		area
	})
	ding.newDing = true;
	ding.save();

	res.end('success');
}

exports.bullSuccess = (req, res, next) => {
	if(!req.session.buller) {
		return res.end('fail');
	}

	var id = req.session.buller._id;

	Ding.getDingsByBuller({
		'king_id': id,
		'newDing': true
	}, (err, dings) => {
		dings.forEach(function(item) {
			Good.getGoodById(item.good_id._id, (err, good) => {

				good.cellNum += 1;
				good.save();
			})

			Buller.getBullerById(id, (err, buller) => {
				buller.score += dings.length * 10;
				buller.save();
			})

			item.money = true;
			item.save();

		})
		res.end('success');
	})

}

exports.noBull = (req, res, next) => {
	if(!req.session.buller) {
		return res.end('fail');
	}
	var page = parseInt(req.query.page);
	if(!page) {
		page = 1;
	}

	var id = req.session.buller._id;

	Ding.getDingsByBuller({
		'king_id': id,
		'money': false
	}, (err, data) => {
		if(err) {
			return res.end(err);
		}

		Ding.find({
			'king_id': id,
			'money': false
		}).populate('seller_id good_id').sort({
			'create_time': -1
		}).skip(6 * (page - 1)).limit(6).exec(function(err, dings) {

			if(err) {
				return res.end(err);
			}

			res.json({
				dings,
				count: data.length
			});

		})

	})

}

exports.removeDing = (req, res, next) => {
	if(!req.session.buller) {
		return res.end('fail');
	}
	var page = parseInt(req.query.page);
	if(!page) {
		page = 1;
	}
	var id = req.query.id;
	var buller_id = req.session.buller._id;

	Ding.remove({
		'_id': id
	}).then((data) => {

		Ding.getDingsByBuller({
			'king_id': buller_id,
			'money': false
		}, (err, datas) => {
			if(err) {
				return res.end(err);
			}

			Ding.find({
				'king_id': buller_id,
				'money': false
			}).populate('seller_id good_id').sort({
				'create_time': -1
			}).skip(6 * (page - 1)).limit(6).exec(function(err, dings) {

				if(err) {
					return res.end(err);
				}

				res.json({
					dings,
					count: datas.length
				});

			})

		})

	}).catch((err) => {
		res.end(err);
	})

}

exports.noSend = (req, res, next) => {
	if(!req.session.buller) {
		return res.end('fail');
	}

	var page = parseInt(req.query.page);
	if(!page) {
		page = 1;
	}

	var id = req.session.buller._id;

	Ding.getDingsByBuller({
		'king_id': id,
		'hasSend': false,
		'money': true
	}, (err, data) => {
		if(err) {
			return res.end(err);
		}

		Ding.find({
			'king_id': id,
			'hasSend': false,
			'money': true
		}).populate('seller_id good_id').sort({
			'create_time': -1
		}).skip(6 * (page - 1)).limit(6).exec(function(err, dings) {

			if(err) {
				return res.end(err);
			}

			res.json({
				dings,
				count: data.length
			});

		})

	})

}
exports.noGet = (req, res, next) => {

	if(!req.session.buller) {
		return res.end('fail');
	}

	var page = parseInt(req.query.page);
	if(!page) {
		page = 1;
	}

	var id = req.session.buller._id;

	Ding.getDingsByBuller({
		'king_id': id,
		'hasSend': true,
		'money': true,
		'hasGet': false
	}, (err, data) => {
		if(err) {
			return res.end(err);
		}

		Ding.find({
			'king_id': id,
			'hasSend': true,
			'money': true,
			'hasGet': false
		}).populate('seller_id good_id').sort({
			'create_time': -1
		}).skip(6 * (page - 1)).limit(6).exec(function(err, dings) {

			if(err) {
				return res.end(err);
			}

			res.json({
				dings,
				count: data.length
			});

		})

	})

}

exports.historyDing = (req, res, next) => {

	if(!req.session.buller) {
		return res.end('fail');
	}

	var page = parseInt(req.query.page);
	if(!page) {
		page = 1;
	}

	var id = req.session.buller._id;

	Ding.getDingsByBuller({
		'king_id': id,
		'hasSend': true,
		'money': true,
		'hasGet': true
	}, (err, data) => {
		if(err) {
			return res.end(err);
		}

		Ding.find({
			'king_id': id,
			'hasSend': true,
			'money': true,
			'hasGet': true
		}).populate('seller_id good_id').sort({
			'create_time': -1
		}).skip(6 * (page - 1)).limit(6).exec(function(err, dings) {

			if(err) {
				return res.end(err);
			}

			res.json({
				dings,
				count: data.length
			});

		})

	})

}

exports.removeHistoryDing = (req, res, next) => {

	if(!req.session.buller) {
		return res.end('fail');
	}

	var page = parseInt(req.query.page);
	if(!page) {
		page = 1;
	}

	var id = req.session.buller._id;

	var ding_id = req.query.id;
	console.log(ding_id)
	Ding.remove({
		'_id': ding_id
	}).then((ding) => {

		Ding.getDingsByBuller({
			'king_id': id,
			'hasSend': true,
			'money': true,
			'hasGet': true
		}, (err, data) => {
			if(err) {
				return res.end(err);
			}

			Ding.find({
				'king_id': id,
				'hasSend': true,
				'money': true,
				'hasGet': true
			}).populate('seller_id good_id').sort({
				'create_time': -1
			}).skip(6 * (page - 1)).limit(6).exec(function(err, dings) {

				if(err) {
					return res.end(err);
				}

				res.json({
					dings,
					count: data.length
				});

			})

		})

	}).catch((err) => {
		res.end(err);
	})

}

exports.dingInfo = (req, res, next) => {
	if(!req.session.buller) {
		return res.end('fail');
	}
	var id = req.query.id;
	Ding.getDingById(id, (err, ding) => {
		if(err) {
			return res.end(err);
		}

		res.json({
			ding
		})

	})

}
exports.toBull = (req, res, next) => {
	if(!req.session.buller) {
		return res.end('fail');
	}

	var id = req.query.id;

	Ding.getDingById(id, (err, ding) => {
		if(err) {
			return res.end(err);
		}

		Good.getGoodById(ding.good_id._id, (err, good) => {

			good.cellNum += 1;
			good.save();
		})
		Buller.getBullerById(req.session.buller._id,(err,buller)=>{
        	buller.score +=  10;
        	buller.save();
        })

		ding.money = true;
		ding.save();

		res.end('success');

	})

}

exports.getDing = (req, res, next) => {
	if(!req.session.buller) {
		return res.end('fail');
	}

	var id = req.query.id;

	Ding.getDingById(id, (err, ding) => {
		if(err) {
			return res.end(err);
		}

		ding.hasGet = true;
		ding.save().then((ding) => {

			var page = parseInt(req.query.page);
			if(!page) {
				page = 1;
			}

			var buller_id = req.session.buller._id;

			Ding.getDingsByBuller({
				'king_id': buller_id,
				'hasSend': true,
				'money': true,
				'hasGet': false
			}, (err, data) => {
				if(err) {
					return res.end(err);
				}

				Ding.find({
					'king_id': buller_id,
					'hasSend': true,
					'money': true,
					'hasGet': false
				}).populate('seller_id good_id').sort({
					'create_time': -1
				}).skip(6 * (page - 1)).limit(6).exec(function(err, dings) {

					if(err) {
						return res.end(err);
					}

					res.json({
						dings,
						count: data.length
					});

				})

			})

		});

	})

}